import { defineStore } from 'pinia'
import { ref } from 'vue'

// 房源数据类型定义
export interface Property {
  id: string
  title: string
  address: string
  type: 'apartment' | 'house' | 'studio' | 'shared'
  area: number
  floor?: number
  rooms: number
  bathrooms: number
  price: number
  deposit?: number
  paymentMethod?: 'monthly' | 'quarterly' | 'semi-annual' | 'annual'
  description?: string
  facilities: string[]
  contactName: string
  contactPhone: string
  status: 'available' | 'rented'
  publishDate: string
  landlordId: string
}

// 发布房源表单数据类型
export interface PropertyForm {
  title: string
  address: string
  type: string
  area: number | null
  floor: number | null
  rooms: number
  bathrooms: number
  price: number | null
  deposit: number | null
  paymentMethod: string
  description: string
  facilities: string[]
  contactName: string
  contactPhone: string
}

export const usePropertyStore = defineStore('property', () => {
  // 房源列表
  const properties = ref<Property[]>([
    // 添加一些示例房源数据
    {
      id: 'demo-1',
      title: '精装修两室一厅',
      address: '临沂外滩10号楼603',
      type: 'apartment',
      area: 85,
      floor: 6,
      rooms: 2,
      bathrooms: 1,
      price: 1500,
      deposit: 1500,
      paymentMethod: 'monthly',
      description: '房屋位置优越，交通便利，精装修，拎包入住',
      facilities: ['空调', '洗衣机', '冰箱', '热水器', '宽带'],
      contactName: '张先生',
      contactPhone: '13800138001',
      status: 'available',
      publishDate: new Date().toISOString(),
      landlordId: 'demo-landlord-1'
    },
    {
      id: 'demo-2',
      title: '温馨单间公寓',
      address: '市中心商业区A座1208',
      type: 'studio',
      area: 45,
      floor: 12,
      rooms: 1,
      bathrooms: 1,
      price: 1200,
      deposit: 1200,
      paymentMethod: 'monthly',
      description: '单间公寓，设施齐全，适合单身人士',
      facilities: ['空调', '热水器', '宽带', '电视'],
      contactName: '李女士',
      contactPhone: '13800138002',
      status: 'available',
      publishDate: new Date().toISOString(),
      landlordId: 'demo-landlord-2'
    },
    {
      id: 'demo-3',
      title: '豪华三室两厅',
      address: '高新区花园小区B栋501',
      type: 'house',
      area: 120,
      floor: 5,
      rooms: 3,
      bathrooms: 2,
      price: 2800,
      deposit: 2800,
      paymentMethod: 'monthly',
      description: '豪华装修，家具家电齐全，环境优美',
      facilities: ['空调', '洗衣机', '冰箱', '热水器', '宽带', '电视', '沙发', '床'],
      contactName: '王先生',
      contactPhone: '13800138003',
      status: 'available',
      publishDate: new Date().toISOString(),
      landlordId: 'demo-landlord-3'
    },
    {
      id: 'demo-4',
      title: '合租房间',
      address: '大学城学生公寓C区',
      type: 'shared',
      area: 25,
      floor: 3,
      rooms: 1,
      bathrooms: 1,
      price: 800,
      deposit: 800,
      paymentMethod: 'monthly',
      description: '合租房间，适合学生，价格实惠',
      facilities: ['空调', '热水器', '宽带', '书桌'],
      contactName: '赵女士',
      contactPhone: '13800138004',
      status: 'available',
      publishDate: new Date().toISOString(),
      landlordId: 'demo-landlord-4'
    }
  ])

  // 添加房源
  const addProperty = (propertyForm: PropertyForm, landlordId: string): Property => {
    const newProperty: Property = {
      id: Date.now().toString(), // 简单的ID生成，实际项目中应该使用UUID
      title: propertyForm.title,
      address: propertyForm.address,
      type: propertyForm.type as Property['type'],
      area: propertyForm.area || 0,
      floor: propertyForm.floor || undefined,
      rooms: propertyForm.rooms,
      bathrooms: propertyForm.bathrooms,
      price: propertyForm.price || 0,
      deposit: propertyForm.deposit || undefined,
      paymentMethod: propertyForm.paymentMethod as Property['paymentMethod'] || undefined,
      description: propertyForm.description,
      facilities: [...propertyForm.facilities],
      contactName: propertyForm.contactName,
      contactPhone: propertyForm.contactPhone,
      status: 'available',
      publishDate: new Date().toISOString(),
      landlordId
    }

    properties.value.push(newProperty)
    
    // 保存到本地存储
    saveToLocalStorage()
    
    return newProperty
  }

  // 获取指定房东的房源
  const getPropertiesByLandlord = (landlordId: string): Property[] => {
    return properties.value.filter(property => property.landlordId === landlordId)
  }

  // 获取所有可租房源
  const getAvailableProperties = (): Property[] => {
    return properties.value.filter(property => property.status === 'available')
  }

  // 更新房源状态
  const updatePropertyStatus = (propertyId: string, status: Property['status']) => {
    const property = properties.value.find(p => p.id === propertyId)
    if (property) {
      property.status = status
      saveToLocalStorage()
    }
  }

  // 更新房源信息
  const updateProperty = (propertyId: string, updates: Partial<Property>) => {
    const property = properties.value.find(p => p.id === propertyId)
    if (property) {
      Object.assign(property, updates)
      saveToLocalStorage()
    }
  }

  // 删除房源
  const deleteProperty = (propertyId: string) => {
    const index = properties.value.findIndex(p => p.id === propertyId)
    if (index > -1) {
      properties.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('properties', JSON.stringify(properties.value))
    } catch (error) {
      console.error('保存房源数据到本地存储失败:', error)
    }
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    try {
      const stored = localStorage.getItem('properties')
      if (stored) {
        properties.value = JSON.parse(stored)
      }
    } catch (error) {
      console.error('从本地存储加载房源数据失败:', error)
      properties.value = []
    }
  }

  // 获取房源统计信息
  const getPropertyStats = (landlordId: string) => {
    const landlordProperties = getPropertiesByLandlord(landlordId)
    return {
      total: landlordProperties.length,
      available: landlordProperties.filter(p => p.status === 'available').length,
      rented: landlordProperties.filter(p => p.status === 'rented').length
    }
  }

  // 房源类型中文名称映射
  const getPropertyTypeName = (type: string): string => {
    const typeNames: Record<string, string> = {
      apartment: '公寓',
      house: '别墅',
      studio: '单间',
      shared: '合租'
    }
    return typeNames[type] || type
  }

  // 付款方式中文名称映射
  const getPaymentMethodName = (method: string): string => {
    const methodNames: Record<string, string> = {
      monthly: '月付',
      quarterly: '季付',
      'semi-annual': '半年付',
      annual: '年付'
    }
    return methodNames[method] || method
  }

  // 初始化时加载数据
  loadFromLocalStorage()

  return {
    properties,
    addProperty,
    getPropertiesByLandlord,
    getAvailableProperties,
    updatePropertyStatus,
    updateProperty,
    deleteProperty,
    getPropertyStats,
    getPropertyTypeName,
    getPaymentMethodName,
    loadFromLocalStorage
  }
})
